package util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import data_structs.Hit;

public class SortedHits {
	
	HashMap<Integer,HashMap<Integer,ArrayList<Hit>>> hits;
	
	public SortedHits() {
		hits = new HashMap<Integer,HashMap<Integer,ArrayList<Hit>>>();
	}
	
	public SortedHits(ArrayList<Hit> unsorted) {
		hits = new HashMap<Integer,HashMap<Integer,ArrayList<Hit>>>();
		sort(unsorted);
	}
	
	public void sort(ArrayList<Hit> unsorted) {
		HashMap<Integer,ArrayList<Hit>> sortedShifts;
		ArrayList<Hit> offsets;
		//Cycle through all hits in array
		//Start at end of array for easy deletion after copying into sorted
		for( int i = unsorted.size()-1; i >= 0; i-- ) {
			Hit hit = unsorted.get(i);
			//Find correct array to store the hit
			if( (sortedShifts = hits.get(hit.id)) == null ) {
				hits.put(hit.id, new HashMap<Integer,ArrayList<Hit>>());
				sortedShifts = hits.get(hit.id);
			}
			
			int shift = hit.getShift();
			if( (offsets = sortedShifts.get(shift)) == null ) {
				sortedShifts.put(shift, new ArrayList<Hit>());
				offsets = sortedShifts.get(shift);
			}
			//When correct array is found, perform insertion sort to add
			offsets = InsertionSort(offsets, hit);
			unsorted.remove(i);
		}
	}
	
	//Insert hit into correct position
	private ArrayList<Hit> InsertionSort(ArrayList<Hit> offsets, Hit hit) {
		int offset = hit.getOffset();
		for( int i = 0; i < offsets.size(); i++ ) {
			if( offset < offsets.get(i).getOffset() ) {
				offsets.add(i,hit);
				return offsets;
			}
		}
		//End of array list reached, add to end
		offsets.add(hit);
		return offsets;
	}
	
	/**
	 * Accessor Methods
	 */
	
	public Set<Integer> getIds() {
		return hits.keySet();
	}
	
	public Set<Integer> getShifts(int id) {
		return (hits.get(id)).keySet();
	}
	
	public ArrayList<Hit> getHits(int id, int shift) {
		return ((hits.get(id)).get(shift));
	}
	
	
	
	
	

}
